package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.Date;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper,ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //1. 参数校验
        dto.checkParam();
        //2.封装查询条件
        //2.1 分页条件
        Page pageReq = new Page<>(dto.getPage(), dto.getSize());
        //2.2 查询条件
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getReason, dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(pageReq, wrapper);
        //3.返回结果 pageResponseRest

        return new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
    }

   // @Transactional //开启事务
    @GlobalTransactional(timeoutMills = 100000,rollbackFor = Exception.class) //RuntimeException.class
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.参数校验 id 不能为空
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名ID不能为空");
        }
        //1.1根据id查询 ap_user_realname
        ApUserRealname realname = getById(dto.getId());
        if (realname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "频道认证信息不存在");
        }
        if (!AdminConstants.WAIT_AUTH.equals(realname.getStatus())) { //如果不等一 说明不是待审核状态
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证信息不是待审核状态");
        }
        //1.2根据ap_user_realname中userId查询ap_user
        ApUser apUser = apUserMapper.selectById(realname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.ADMING_CHANNEL_NOT_EXIST, "该实名认证信息不存在");
        }
        //2.修改ap_user_realname表status状态
        realname.setStatus(status);
        if (StringUtils.isNotEmpty(dto.getMsg())) {
            realname.setReason(dto.getMsg());
        }
        updateById(realname);
        //3. 如果状态为9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //3.1 开通自媒体账户信息
            WmUser wmUser = createWmUser(apUser);
            //3.2 创建作者信息
            createAuthor(apUser,wmUser);
        }

//        System.out.println(1/0);
//        new Exception("12321222");

        return ResponseResult.okResult();
    }
    @Autowired
    ArticleFeign articleFeign;
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if (result.getCode().intValue()!=0){ //说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        ApAuthor apAuthor = result.getData();
        if (apAuthor!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        // 2. 如果不存在 就 创建作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2); // 平台自媒体人
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult saveResult = articleFeign.save(apAuthor);
        if(saveResult.getCode().intValue() != 0) { // 说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, result.getErrorMessage());
        }
    }

    @Autowired
    WemediaFeign wemediaFeign;

    private WmUser createWmUser(ApUser apUser) {
        //1.根据用户名 查询 wmUser 是否已经创建
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (result.getCode().intValue() != 0) { //说明远程调用失败
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        if (wmUser != null) {
            //2.如果已经创建 抛异常数据存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        //3.创建wnUser信息 保存
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser, wmUser);
        wmUser.setApUserId(apUser.getId()); // 关联的app账户id
        wmUser.setNickname(apUser.getName()); // 昵称
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> responseResult = wemediaFeign.save(wmUser);
        if (responseResult.getCode().intValue() != 0) { // 说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, result.getErrorMessage());
        }
        return responseResult.getData();//返回保存成功的自媒体账户信息
    }
}
